package net.gz01.wallet.web.controller.admin;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

import javax.imageio.ImageIO;
import net.gz01.util.ZOExcel;
import net.gz01.util.ZOJson;
import net.gz01.util.ZOLog;
import net.gz01.wallet.web.config.SystemEnum;
import net.gz01.wallet.web.model.*;
import net.gz01.wallet.web.model.Dictionary;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

import lombok.extern.slf4j.Slf4j;
import net.gz01.util.ZODate;
import net.gz01.wallet.common.Certificate;
import net.gz01.wallet.common.PageRespon;
import net.gz01.wallet.common.ZOSearchCondition;
import net.gz01.wallet.message.AccountBalanceChangeResp;
import net.gz01.wallet.web.config.SystemConfig;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.service.AccountService;
import net.gz01.wallet.web.service.SendSMSConfig;
import org.jxls.common.Context;

@Slf4j
public class PayOrderExportController extends BaseController {
    private AccountService accountService = Duang.duang(AccountService.class);

    public void search() {
        List<Dictionary> dictionaryList = Dictionary.dao.selectBizType();
        List<Dictionary> bizTypeList = new ArrayList<>();

        for(Dictionary dictionary : dictionaryList){
            if(SystemEnum.BizType.DF_Personal.getValue().equals(dictionary.getCode()) ||
                    SystemEnum.BizType.DF_Company.getValue().equals(dictionary.getCode()) ||
                    SystemEnum.BizType.Withdraw_Personal.getValue().equals(dictionary.getCode()) ||
                    SystemEnum.BizType.Withdraw_Company.getValue().equals(dictionary.getCode())){
                bizTypeList.add(dictionary);
            }
        }
        String startTime = ZODate.getPlusDays(ZODate.getDate(), -1).toString() + " " +
                "14:00:00";

        String EndTime = ZODate.getDate() + " " + "14:00:00";
        setAttr("startTime", startTime);
        setAttr("endTime", EndTime);
        setAttr("bizTypeList", bizTypeList);
        setAttr("orderStatusList", Dictionary.dao.selectOrderStatus());
        setAttr("amtLimit", Dictionary.dao.getAmtLimit());
        render("clearing/payexport/payOrderList.html");
    }

    public void listJson() {
        ZOSearchCondition sc = super.getSearchCondition();
        String myBizType = sc.getStr("dgds"); //1:对公， 2:对私
        if("1".equals(myBizType)){
            sc.setParameter("bizType", SystemEnum.BizType.DF_Company.getValue());
            sc.setParameter("bizType2", SystemEnum.BizType.Withdraw_Company.getValue());
        }else {
            sc.setParameter("bizType", SystemEnum.BizType.DF_Personal.getValue());
            sc.setParameter("bizType2", SystemEnum.BizType.Withdraw_Personal.getValue());
        }
        if(StringUtils.isEmpty(sc.getStr("createTimeStart"))) {
            String createTimeStart = ZODate.getPlusDays(ZODate.getDate(), -1).toString() + " " +
                    "14:00:00";
            sc.put("createTimeStart", createTimeStart);
        }

        if(StringUtils.isEmpty(sc.getStr("createTimeEnd"))) {
            String createTimeEnd = ZODate.getDate() + " " + "14:00:00";
            sc.put("createTimeEnd", createTimeEnd);
        }
        sc.put("orderStatus", SystemEnum.OrderStatus.WaitTransferOut.getValue());
        Page<TradeOrder> pageResult = TradeOrder.dao.search(sc);
        renderJson(new PageRespon(pageResult));
    }

/*
批量审核成功的
 */
    @Before(Tx.class)
    public void toTransferOutList(){
        String res = getPara("num");
        String orderList = getPara("orderNoList");
        ZOLog.api.info("收到批量处理打款数据:"+ res + "---" + orderList);

        int num = Integer.parseInt(res);
        String[] orderNoStr = orderList.split(";");

        List<TradeOrder> tradeOrderList = new ArrayList<> ();
        for(int i = 0; i < num; i++){
            TradeOrder tradeOrder = TradeOrder.dao.selectByOrderNo(orderNoStr[i]);
            if(tradeOrder == null){
                renderFail("订单号:" + orderNoStr[i] + "不存在!!");
                return;
            }
            if (SystemEnum.BizType.DF_Company.getValue().equals(tradeOrder.getBizType())
                    || SystemEnum.BizType.DF_Personal.getValue().equals(tradeOrder.getBizType())
                    || SystemEnum.BizType.Withdraw_Company.getValue().equals(tradeOrder.getBizType())
                    || SystemEnum.BizType.Withdraw_Personal.getValue().equals(tradeOrder.getBizType())){
                tradeOrderList.add(tradeOrder);
            }else {
                renderFail("订单号:" + orderNoStr[i] + "不属于对公或者对私转账，钱包内转账不能批量操作!");
                return;
            }
        }
        StringBuffer resp = new StringBuffer();

        for(TradeOrder item: tradeOrderList){
            item.setOrderStatus(SystemEnum.OrderStatus.Success.getValue());
            item.setRespCode(SystemEnum.Resp.Success.getCode());
            item.setRespMsg(SystemEnum.Resp.Success.getMsg());
            item.setPayTime(ZODate.getDateTime());
            // TODO 把订单发送到付款渠道
            log.info("订单" + item.getOrderNo() + "发往渠道" + item.getChannelCode());
            item.update();
            resp.append("订单:" + item.getOrderNo() + "付款成功<br>");
            MerchUser user = MerchUser.dao.selectByMerCode(item.getMerchCode());
            long realAmt = Math.abs(item.getAmount()) + item.getFee();// 钱包总支出的金额
            SendSMSConfig.senSMSSubAmt(user.getUserName(), realAmt + "", item.getBalance() + "");
        }
        renderSuccess(resp.toString());
    }

    public void report() throws Exception{
        List<Dictionary> payTypeList = Dictionary.dao.selectBizType();
        Map<String, String> payTypeMap = new HashMap<>();
        for (Dictionary payType : payTypeList) {
            payTypeMap.put(payType.getCode(), payType.getName());
        }
        Map<String, String> orderStatus = new HashMap<>();
        for (SystemEnum.OrderStatus os : SystemEnum.OrderStatus.values()) {
            orderStatus.put(os.getValue(), os.getName());
        }

        ZOSearchCondition sc = super.getSearchCondition();

        sc.put("orderStatus", SystemEnum.OrderStatus.WaitTransferOut.getValue());//只需要导出待打款的。
        String fileName = "pay" + ZODate.getDateTime().replace(":", "-");
        String templatePath = SystemEnum.FilePath.ReportTemplate.getValue() + "pay_trade_details.xlsx";
        String targetPath = SystemEnum.FilePath.ReportTmp.getValue() + fileName + ".xlsx";
        LinkedHashMap<String, Context> sheetNameAndData = new LinkedHashMap<>();

        String myBizType = sc.getStr("dgds"); //1:对公， 2:对私
        if("1".equals(myBizType)){
            sc.setParameter("bizType", SystemEnum.BizType.DF_Company.getValue());
            sc.setParameter("bizType2", SystemEnum.BizType.Withdraw_Company.getValue());
        }else {
            sc.setParameter("bizType", SystemEnum.BizType.DF_Personal.getValue());
            sc.setParameter("bizType2", SystemEnum.BizType.Withdraw_Personal.getValue());
        }

        int loop = 1;
        String[] templateSheetName = new String[loop];
        for(int i = 0; i < loop; i++){
            int sheetIndex = i + 1;
            templateSheetName[i] = "Sheet" + sheetIndex;
        }
        Map<String, Object> data = new HashMap<>();
        //循环遍历交易类型
        List<TradeOrder> orderNoList = new ArrayList<>();
        for(int t = 0; t < loop; t++) {
            String name = "";
            if("2".equals(myBizType)){
                name = "对私待打款";
                sc.put("bizType", SystemEnum.BizType.Withdraw_Personal.getValue());
                sc.put("bizType2", SystemEnum.BizType.DF_Personal.getValue());//导出一种交易类型
            }else if("1".equals(myBizType)) {
                name = "对公待打款";
                sc.put("bizType", SystemEnum.BizType.Withdraw_Company.getValue());
                sc.put("bizType2", SystemEnum.BizType.DF_Company.getValue());//导出一种交易类型
            }
            List<TradeOrder> items = TradeOrder.dao.searchReportForAdmin(sc);

            for (TradeOrder item : items) {
                orderNoList.add(item);
                item.setOrderStatus(orderStatus.get(item.getOrderStatus()));
            }
            Context context = new Context();
            context.putVar("list", items);
            sheetNameAndData.put(name, context);
        }
        ZOExcel.exportLargeData(templatePath, targetPath, sheetNameAndData, templateSheetName);
        renderSuccess("/upload/report/tmp/" + fileName + ".xlsx", data);
    }
}
